package upload

import (
	"cgs-server/helper"
	file2 "cgs-server/pkg/file"
	"cgs-server/server"
	"errors"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"
)

type LocalFileStore struct {
}

func (LocalFileStore) Upload(file io.Reader, filename string, fileSize int64, fileType string) (string, error) {
	fileExt := filepath.Ext(filename)

	now := time.Now()
	v4, err := uuid.NewV4()
	if err != nil {
		return "", err
	}
	u1 := v4.String()
	u1 = strings.ReplaceAll(u1, "-", "")
	filename = u1 + fileExt

	savePath := fmt.Sprintf("/Upload/File/%s", helper.TimeToString(now, "yyyyMMdd"))
	physicalPath := server.MapPath(savePath)

	err = file2.IsNotExistMkDir(physicalPath)
	if err != nil {
		return "", err
	}
	targetPath := fmt.Sprintf("%v/%v", physicalPath, filename)
	target, err := os.Create(targetPath)
	if err != nil {
		return "", err
	}
	defer target.Close()

	_, err = io.Copy(target, file)
	if err != nil {
		return "", err
	}

	url := fmt.Sprintf("%s/%s", savePath, filename)

	return url, nil
}

func (LocalFileStore) Delete(key string) error {
	targetPath := server.MapPath(key)
	if file2.CheckNotExist(targetPath) {
		return nil
	}

	if err := file2.Remove(targetPath); err != nil {
		return err
	}

	return nil
}

func (LocalFileStore) Get(key string) (io.Reader, error) {
	targetPath := server.MapPath(key)
	if file2.CheckNotExist(targetPath) {
		return nil, errors.New("file not exist")
	}

	file, err := os.Open(targetPath)
	return file, err
}
